<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\facade\Url;
use app\common\model\DuiBa;
use app\api\model\Banner;
use app\api\model\Article;
use app\api\model\Version;
use app\api\model\TelCode;

use app\api\validate\CheckValidate;


/**
 * 可直接访问的
 * Class Login
 * @package app\api\controller
 */
//header('Content-type: application/x-apple-aspen-config; chatset=utf-8');
//header('Content-Disposition: attachment; filename="company.mobileconfig"');
class Api extends Controller
{
    public function index(){
        return $this->fetch();
    }
    
    
    /**
    * udid回调
    */
    public function callbackUdid(){
        $data = file_get_contents('php://input');
        $plistBegin   = '<?xml version="1.0"';
        $plistEnd   = '</plist>';
        $pos1 = strpos($data, $plistBegin);
        $pos2 = strpos($data, $plistEnd);
        $data2 = substr ($data,$pos1,$pos2-$pos1);
        $xml = xml_parser_create();
        xml_parse_into_struct($xml, $data2, $vs);
        xml_parser_free($xml);

        $UDID = "";

        $CHALLENGE = "";

        $DEVICE_NAME = "";

        $DEVICE_PRODUCT = "";

        $DEVICE_VERSION = "";

        $iterator = 0;

        $arrayCleaned = array();
        foreach($vs as $v){
            if($v['level'] == 3 && $v['type'] == 'complete'){

            $arrayCleaned[]= $v;

            }
        $iterator++;

        }

        $data = "";
        $iterator = 0;

        foreach($arrayCleaned as $elem){

            $data .= "\n==".$elem['tag']." -> ".$elem['value']."<br/>";

            switch ($elem['value']) {

                case "CHALLENGE":

                    $CHALLENGE = $arrayCleaned[$iterator+1]['value'];

                    break;

                case "DEVICE_NAME":

                    $DEVICE_NAME = $arrayCleaned[$iterator+1]['value'];

                    break;

                case "PRODUCT":

                    $DEVICE_PRODUCT = $arrayCleaned[$iterator+1]['value'];

                    break;

                case "UDID":

                    $UDID = $arrayCleaned[$iterator+1]['value'];

                    break;

                case "VERSION":

                    $DEVICE_VERSION = $arrayCleaned[$iterator+1]['value'];

                    break;                       

                }
                $iterator++;

        }

        $params = "UDID=".$UDID."&CHALLENGE=".$CHALLENGE."&DEVICE_NAME=".$DEVICE_NAME."&DEVICE_PR ODUCT=".$DEVICE_PRODUCT."&DEVICE_VERSION=".$DEVICE_VERSION;
        
        $udid = $UDID;
        $time = time();
        $sql = "insert sy_udid(udid, created) select '$udid', $time from DUAL   where  NOT EXISTS (select udid from sy_udid  where udid = '$udid')";
        //file_put_contents('udidsql',$sql,FILE_APPEND);
        Db::execute($sql);
        //file_put_contents('calludid',$params);
        //header("Location: http://dev.skyfox.org/udid?data=".rawurlencode($params));
        //header('HTTP/1.1 301 Moved Permanently');
        //header("Location: http://dev.skyfox.org/udid/index.php?".$params);
        //$data = file_get_contents('php://input');
        //这里可以进行xml解析
        //header("Location: http://dev.skyfox.org/udid?data=".rawurlencode($data)); //有人说必须得目录形式才会安装成功
        
        $url = "https://chengdusy.com/api/api/receiveUdid?".$params;
        //file_put_contents('urludid',$url,FILE_APPEND);
        //header("Location:http://chengdusy.com/api/api/receiveUdid?".$params);
        header('HTTP/1.1 301 Moved Permanently');  //这里一定要301跳转,否则设备安装会提示"无效的描述文件"
        //$this->redirect($url);
        header("Location:$url");exit;
    }
    
    /**
    * 接收udid数据
    */
    public function receiveUdid(){
        $request = $this->request->get();
        //var_dump($request);die;
        //file_put_contents('udidtest',json_encode($request),FILE_APPEND);
        $udid = $request['UDID'];
        //$UDID =  $_GET['UDID'] ? $_GET['UDID'] : $_POST['UDID'];
        $time = time();
        //$sql = "insert sy_udid(udid, created) select '$udid', $time from sy_udid u where (select IFNULL(count(uu.id), 0) from sy_udid uu where uu.udid = '$udid') = 0";
        //echo $sql;die;
        //file_put_contents('udidsql',$sql,FILE_APPEND);
        //Db::execute($sql);
        /*$this->assign([
            'udid' => $udid,
        ]);*/
        //$url = 'http://39.107.97.217:81/#/pages/index/index?udid='.$udid;
        $url = 'cdsyofferwall://'.$udid;
        header("Location:$url");exit;
        //return $this->fetch('receive');
    }
    
    
    /**
    * 下载mobileconfig的网页
    */
    public function download(){
        $url = $this->request->root(true);
        $url .= "/udid.mobileconfig";
        header("Location: $url");
    }
    
    /**
    * 兑吧:积分消费请求
    */
    public function parseCreditConsume(){
        $request = $this->request->get();

        //file_put_contents('test', json_encode($request,JSON_UNESCAPED_UNICODE), FILE_APPEND);
    
        $model = new DuiBa;
        $params = $model->parseCreditConsume($request);
        $errorMessage='';
        if(!$params){
            $errorMessage = $model->getError();
        }
        $status = 'ok';//状态根据自己逻辑返回
        $credits = '10000';//此处填写用户剩余积分
        
        $bizId = date("YmdHis").mt_rand(1000000,9999999);//此处开发者自己创建订单号，不要重复响应
        $result = array ('credits'=>$credits,'status'=>$status,'bizId'=>$bizId,'errorMessage'=>$errorMessage);

        return json_encode($result);
        //file_put_contents('result_test', json_encode($params,JSON_UNESCAPED_UNICODE), FILE_APPEND);
    }
    
    /**
    * 反馈兑换结果请求
    */
    public function parseCreditNotify(){
        $request = $this->request->get();
        
        //file_put_contents('test1', json_encode($request,JSON_UNESCAPED_UNICODE),FILE_APPEND);

        //$str ='{"uid":"74I3ERKFUX","success":"false","errorMessage":"扣积分失败，开发者服务器异常。向开发者请求扣积分，网络请求出错","bizId":"","sign":"e14d6681246bdb1364529ab4a7f4f949","orderNum":"115040236151118C0772","appKey":"2rXPX2hQA93HhMeZqN7ThorV4kCE","timestamp":"1573196793977"}';
        //$request= json_decode($str, true);
        $model = new DuiBa;
        $ret = $model->parseCreditNotify($request);

        if($ret){
            echo 'ok ';
            file_put_contents('result_test1', json_encode($ret,JSON_UNESCAPED_UNICODE), FILE_APPEND);
        }else{
            $error = $model->getError();
            file_put_contents('error_log1', $error, FILE_APPEND);
        }
        
    }
    
    /**
    * bannr图
    */
    public function bannerList(){
        $model = new Banner;
        $request = $this->request->post();
        if(empty($request['type'])){
            die(apiError('缺少参数'));
        }
        $type = (int)$request['type'];
        $where = [
            'type_id' => $type,
            'status' => 1,
        ];
        $list = $model->_list($where);
        return apiSuccess($list);
    }
    
    /**
    * 检测是否更新
    */
    public function checkUpdate(){
        $request = $this->request->post();
        if(!isset($request['num'])){
            die(apiError('缺少参数'));
        }
        
        $num = $request['num'];
        $model = new Version;
        $ret = $model->_checkUpdate($num);
        if($ret){
            return apiSuccess($ret, '请更新', 100);
        }
        return apiSuccess([], '无需更新', 101);
    }
    
    
    /**
    * 首页滚动通知
    */
    public function indexNotice(){
        $model = new Article;
        $list = $model->_indexNotice();
        return apiSuccess($list);
    }
    
    
     /**
    * 发送短信:当关闭短信时默认验证码为123456
    */
    public function sendSms(){
        $request = $this->request->post();
        $validate = new CheckValidate();
        if(!$validate->scene($validate::SCENE_SEND_MSG)->check($request)){
            return apiError($validate->getError());
        }
        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
        $code = rand(1111,9999);
        $mobile = $request['tel'];
        $smsConf = array(
            'key'   => '826b6a1e018635ce9bbbd3706f92169d', //您申请的APPKEY
            'mobile'    => $mobile, //接受短信的用户手机号码
            'tpl_id'    => '202558', //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>'#code#='.$code //您设置的模板变量，根据实际情况修改
        );
        $today = strtotime(date('Y-m-d'));
        //判断今日发短信次数
        $maps['tel']     = $mobile;
        $maps['created'] = ['gt',$today];
        $count = Db::name('tel_code')->where($maps)->count();
        if($count>10){
            return apiSuccess([], '今日发短信次数过多', 201);
        }
        $content = $this->juhecurl($sendUrl,$smsConf,1); //请求发送短信
        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                $insert['type']   = $request['type'];
                $insert['tel']    = $mobile;
                $insert['code']   = $code;
                Db::name('tel_code')->insert($insert);
                return apiSuccess([], '发送成功', 200);
            }else{
                //状态非0，说明失败
                $msg = $result['reason'];
                $back_msg = "短信发送失败(".$error_code.")：".$msg;
                return apiSuccess([], $back_msg, 201);
            }
        }else{
            return apiSuccess([], '发送失败', 201);
        }
    }


    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    private function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }
}